import axios from 'axios'
import { showToast } from 'vant'

import { host } from '@/constant'
import store from '@/store/index.js'
import md5 from 'js-md5/src/md5.js'
// import * as uniApp from '/utils/uni.webview.1.5.4.js'


// 不知为何，此处使用 import router from "@/router" 无效

// 创建axios实例
const service = axios.create({
    baseURL: host,
    timeout: 30000 // 请求超时时间
})

let u = navigator.userAgent;
let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
let sign = function (param) {

    var json = '';
    var keys = Object.keys(param).sort();
    keys.forEach((data) => {

        if (param[data] === '' || param[data] === null) {
            json = json + '';
        } else {
            if (data === 'activityList') {
                const result = param[data].map(obj => `{activityId=${obj.activityId}, backAmount=${obj.backAmount}, activityName=${obj.activityName}}`).join(', ');
                json = json + data + '=[' + result + ']&';
            } else if (data !== 'pageStart' && data !== 'pageSize' && data !== 'terList') {
                json = json + data + '=' + param[data] + '&';
            }
        }
    });
    // console.log(json)
    if (json === '') {
        return 'mt';
    } else {
        return md5(json + 'MT08888888888');
    }
};
// let sign = function (param) {
// 	// console.log(param)
// 	var json = ''
// 	var keys = Object.keys(param).sort()
// 	keys.forEach((data) => {
// 		if (param[data] === '' || param[data] === null) {
// 			json = json + ''
// 		} else {
// 			if (data == 'activityList') {
// 				// .toString()
// 				// param[data].value.map(item => item.name).join(', ');
// 				// const result = []
// 				result[0]=param[data].map(obj => `{activityId=${obj.activityId}, backAmount=${obj.backAmount}, activityName=${obj.activityName}}`).join(',');
// 				// console.log(result)
// 				param[data] = result[0]
// 			}
// 			if (data != 'pageStart' && data != 'pageSize' && data != 'terList') {
// 				json = json + data + '=' + param[data] + '&'
// 			}
// 		}
// 	})
// 	console.log(json)
// 	if (json == '') {
// 		return 'mt'
// 	} else {
// 		return md5(json + 'MT08888888888')
// 	}
// }
// request拦截器
service.interceptors.request.use(
    config => {
        const token = store.state.user.token
        console.log(config)
        if (config.url != "/unionfit/getCardBin" && config.url != "/posTer/selectTerList" && config.url != "/posMerchant/selectMerChannelList" && config.url != "/posAgent/selectUnderAgentList" && config.url != "/posAgent/addAgent" && config.url != "/file/addFile" && config.url != "/posAgent/selectOpenChannel" && config.url != "/posAgent/selectAgentChannelRate" && config.url != "/posAgent/updateAgentChannelRate" && config.url != "/posAgent/openChannel" && config.url != "/posTer/updateTerTran" && config.url != "/posTer/updateTerTranRange" && config.url != "/posAgent/selectUnderAgentRate" && config.url != "/posAgent/selectUnderAllAgentList" && config.url != "/posOrder/selectPosOrderByld" && config.url != "/posAgent/selectAgentPublicizeInf" && config.url != "/posMerSum/selectMerchantSummary" && config.url != "/posMerchant/selectMerchantChannel" && config.url != "/posAgent/selectAgentChannel" && config.url != "/posAgentSum/selectAgentData" && config.url != "/posTer/selectTerListByChannel" && config.url != "/posTer/selectTerAlertList" && config.url != "/posCommon/alOcr") {

            let agentNo = store.state.user.agentNo
            let agent = {
                'agentNo': agentNo
            }
            Object.assign(config.data, agent)
        }


        // config.headers.appVersion = '1.0.0'
        config.headers['Content-Type'] = 'application/json;charset=UTF-8'
        config.headers['Access-Control-Allow-Origin'] = '*'
        config.headers['sign'] = sign(config.data)
        config.headers['sysType'] = store.state.user.os
        config.headers['version'] = store.state.user.version
        config.headers['userNo'] = store.state.user.agentNo
        if (token) {
            config.headers['Token'] = token // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
        }
        if (!store.state.data.Loading) {
            store.dispatch('data/GetLoading', true)
        }

        return config
    },
    error => {
        // Do something with request error
        console.log(error) // for debug
        Promise.reject(error)
    }
)

// respone拦截器
service.interceptors.response.use(
    /**
     * 下面的注释为通过response自定义code来标示请求状态，当code返回如下情况为权限有问题，登出并返回到登录页
     * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中
     */
    response => {
        store.dispatch('data/GetLoading', false)
        // console.log('asd',response)
        document.addEventListener("UniAppJSBridgeReady", function () {
            uni.postMessage({
                data: {
                    options: '来自H5的问候'
                }
            });
        });
        const res = response.data
        // 登录过期拦截
        if (response.data.code !== '000000' && response.data.code !== 91) {
            showToast({
                message: response.data.message,
                duration: 5 * 1000
            })
            return Promise.reject(response.data)
        } else if (response.data.code == '-A00005') {
            document.addEventListener("UniAppJSBridgeReady", function () {
                uniApp.postMessage({
                    data: {
                        options: '来自H5的问候'
                    }
                });
            });
        } else {
            return response.data
        }
    },
    error => {
        store.dispatch('data/GetLoading', false)
        console.log('err' + error) // for debug
        showToast({
            message: error.message,
            position: 'bottom',
            duration: 5 * 1000
        })

        return Promise.reject(error)
    }
)

export default service